package com.NyCloud.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.NyCloud.entity.Location;
import com.NyCloud.service.ILocationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.NyCloud.entity.User;
import com.NyCloud.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;

@RestController
@CrossOrigin
@Api(tags = "身份认证")
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ILocationService locationService;

    @PostMapping("/login")
    @ApiOperation("登录")
    public SaResult login(@RequestBody  User user) {
        User foundUser = userService.getOne(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        if (foundUser == null) {
            return SaResult.error("账号不存在！");
        }
        if (foundUser.getPassword().equals(user.getPassword())) {
            StpUtil.login(foundUser.getId());
            StpUtil.getSession().set("role", foundUser.getRole());
            StpUtil.getSession().set("user", foundUser);
            HashMap<String, Object> map = new HashMap<>();
            map.put("user", foundUser);
            map.put("token", StpUtil.getTokenInfo());
            return SaResult.data(map);
        } else {
            return SaResult.error("密码错误！");
        }
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public SaResult register(@Valid @RequestBody User user) {
        userService.save(user);
//       位置信息
        Location location = new Location();
        location.setUserId(user.getId());
        locationService.save(location);
        return SaResult.ok();
    }

    @SaCheckLogin
    @GetMapping("/demo1")
    @ApiOperation("需要登录后访问")
    public SaResult demo1(){
        return SaResult.ok("你好呀");
    }

    @SaCheckRole("admin")
    @GetMapping("/demo2")
    @ApiOperation("admin角色可访问")
    public SaResult checkRole(){
        return SaResult.ok("admin角色，可以看到");
    }

    @ApiOperation("退出")
    @GetMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
}
